package com.sxbbc.common.core.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import com.sxbbc.common.basics.service.redis.RedisUtilsService;
import com.sxbbc.common.core.entity.jz.*;
import com.sxbbc.common.core.enums.*;
import com.sxbbc.common.core.mapper.jz.CAccountMapper;
import com.sxbbc.common.core.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.function.common.GetRest;
import com.function.common.RestResponse;
import com.sxbbc.common.basics.exceptions.ThrowJsonException;
import com.sxbbc.common.basics.utils.calculation.CalcuUtils;
import com.sxbbc.common.basics.utils.statics.StaticUtils;
import com.sxbbc.common.core.alipay.AlipayUtils;
import com.sxbbc.common.core.dto.jz.FreezeVo;
import com.sxbbc.common.core.dto.jz.RefundVo;
import com.sxbbc.common.core.mapper.jz.OrderExpDetailMapper;
import com.sxbbc.common.core.mapper.jz.OrderRefundLogMapper;
import com.sxbbc.common.core.service.system.mode.ModeService;
import com.sxbbc.common.core.service.system.redis.listener.OrderListerService;
import com.sxbbc.common.core.utils.BasePage;
import com.sxbbc.common.core.utils.RedisUtils;
import com.sxbbc.common.core.wx.WxPayUtils;

/**
 * <p>
 * 订单退款记录表 服务实现类
 * </p>
 *
 * @author xiaoky
 * @since 2019-05-11
 */
@Service
public class OrderRefundLogServiceImpl extends ServiceImpl<OrderRefundLogMapper, OrderRefundLog> implements IOrderRefundLogService {

    @Autowired
    private IAccountChangeService iAccountChangeService;
    @Autowired
    private CAccountMapper cAccountMapper;
    @Autowired
    private ICCustomerService cCustomerService;
    @Autowired
    private IOrderDetailService orderDetailService;
    @Autowired
    private IOrderMainService orderMainService;
    @Autowired
    private IBLoginService bLoginService;
    @Autowired
    private OrderRefundLogMapper orderRefundLogMapper;
    @Autowired
    private ICPayLogService cPayLogService;
    @Autowired
    private IAccountChangeService accountChangeService;
    @Autowired
    private OrderListerService orderListerService;
    @Autowired
    private IOrderConfigGroupService orderConfigGroupService;
    @Autowired
    private RedisUtilsService redisUtilsService;
    @Autowired
    private IPushService pushService;
    @Autowired
    private OrderExpDetailMapper orderExpDetailMapper;
    @Autowired
    private ModeService modeService;

    @Override
    public IPage<OrderRefundLog> queryRefunds(BasePage<OrderRefundLog> page, QueryWrapper<OrderRefundLog> wrapper) {
        IPage<OrderRefundLog> pageInfo = super.page(page, wrapper);
        for (OrderRefundLog refund : pageInfo.getRecords()) {
            // 相关用户
            CCustomer customer = cCustomerService.getById(refund.getCid());
            if (customer != null) {
                refund.setCNickName(customer.getNickName());
            }

            // 退款图片
            if (!StringUtils.isEmpty(refund.getRefundImgs())) {
                refund.setRefundImgList(Arrays.asList(refund.getRefundImgs().split(",")));
            }
        }
        return pageInfo;
    }

    @Override
    public RestResponse handleRefundRefect(Integer refundId, String rejectRemark, Integer checkId) {
        CalcuUtils calcuUtils = CalcuUtils.getInstance();
        OrderRefundLog refundLog = super.getById(refundId);
        if (refundLog == null) {
            return GetRest.getFail("退款信息不存在");
        }
        if (StringUtils.isBlank(rejectRemark)) {
            return GetRest.getFail("请输入驳回理由");
        }
        // 校验退款状态
        if (!calcuUtils.isEquals(refundLog.getStatus(), StaticUtils.STATUS_APPLY)) {
            return GetRest.getFail("重复操作");
        }
        refundLog.setRejectRemark(rejectRemark);
        refundLog.setCheckTime(new Date());
        refundLog.setStatus(StaticUtils.STATUS_FAIL);
        // 操作人
        refundLog.setCheckId(checkId);
        // 退款表状态修改
        boolean result = super.updateById(refundLog);
        if (result) {
            OrderDetail orderDetail = orderDetailService.getById(refundLog.getOrderDetailId());
            if (orderDetail == null) {
                throw new ThrowJsonException("退款驳回失败  Code:001");
            }
            orderDetail.setRefund(StaticUtils.STATUS_NO);
            result = orderDetailService.updateById(orderDetail);
            if (!result) {
                throw new ThrowJsonException("退款驳回失败 Code:002");
            }

            QueryWrapper<OrderMain> orderMainQueryWrapper = new QueryWrapper<>();
            orderMainQueryWrapper.eq("order_code", orderDetail.getOrderCode());
            OrderMain orderMain = orderMainService.getOne(orderMainQueryWrapper);

            //用户扣除创业分给平台拨给用户创业分
            if (orderMain != null && orderDetail.getPoint() != null && BigDecimal.ZERO.compareTo(orderDetail.getPoint()) < 0) {
                BigDecimal totalPoint = calcuUtils.mul(orderDetail.getPoint(), new BigDecimal(orderDetail.getQty()), 2);
                String msg = iAccountChangeService.insertCPointDetail(orderMain.getCid(), HandleTypeEnums.ORDER_REFUND_REFUSE.getId(), StaticUtils.PAY_IN,
                        orderMain.getPayCode(), totalPoint, HandleTypeEnums.getName(HandleTypeEnums.ORDER_REFUND_REFUSE.getId()), orderMain.getCid());
                if (!StringUtils.isEmpty(msg)) {
                    throw new ThrowJsonException(msg);
                }
            }

            return GetRest.getSuccess("退款驳回成功");

        }
        return GetRest.getFail("退款驳回失败");
    }

    @Override
    public RestResponse handleRefundSuccess(Integer refundId, Integer checkId) {
        OrderRefundLog refundLog = super.getById(refundId);
        if (refundLog == null) {
            return GetRest.getFail("退款信息不存在");
        }
        if (!CalcuUtils.getInstance().isEquals(checkId, StaticUtils.STATUS_NO)) {
            BLogin bLogin = bLoginService.getById(checkId);
            if (bLogin == null || !CalcuUtils.getInstance().isEquals(refundLog.getBid(), bLogin.getBid())) {
                return GetRest.getFail("非法操作");
            }
        }
        // 校验退款状态
        if (!CalcuUtils.getInstance().isEquals(refundLog.getStatus(), StaticUtils.STATUS_APPLY)) {
            return GetRest.getFail("重复操作");
        }

        refundLog.setCheckTime(new Date());
        refundLog.setCheckId(checkId);
        refundLog.setStatus(StaticUtils.STATUS_SUCCESS);
        // 退款表状态修改
        boolean result = super.updateById(refundLog);
        if (result) {
            this.handleOrderRefund(refundLog.getOrderDetailId(), null);
            return GetRest.getSuccess("退款通过成功");
        }
        return GetRest.getFail("退款失败");
    }

    /**
     * 同意退款——处理订单数据
     *
     * @param orderDetailId 订单详情Id
     */
    private void handleOrderRefund(Integer orderDetailId, Integer cid) {
        // 订单详情
        OrderDetail orderDetail = orderDetailService.getById(orderDetailId);
        if (orderDetail == null) {
            throw new ThrowJsonException("退款失败：ID【" + orderDetailId + "】的订单明细信息获取失败");
        }

        // 订单信息
        OrderMain order = orderMainService.getByOrderCode(orderDetail.getOrderCode());
        if (order == null) {
            throw new ThrowJsonException("退款失败：订单号【" + orderDetail.getOrderCode() + "】的订单信息获取失败");
        }
        CalcuUtils calcuUtils = CalcuUtils.getInstance();
        if (cid != null && !calcuUtils.isEquals(cid, order.getCid())) {
            throw new ThrowJsonException("退款失败：订单用户信息不一致");
        }
        orderDetail.setRefund(StaticUtils.STATUS_SUCCESS);
        Boolean result = orderDetailService.updateById(orderDetail);
        if (!result) {
            throw new ThrowJsonException("退款失败：ID【" + orderDetailId + "】的订单明细修改退款状态失败");
        }

        // 发货单保存商品退款记录
        // 通过订单编号和商品id查询对应的发货单
        OrderExpDetail expDetail = null;
        try {
            expDetail = orderExpDetailMapper.queryExpByCodeAndPro(order.getOrderCode(), orderDetail.getProDetailId());
            if (StringUtils.isBlank(expDetail.getRefundDetailId())) {
                expDetail.setRefundDetailId(String.valueOf(orderDetail.getProDetailId()));
            } else {
                expDetail.setRefundDetailId(expDetail.getRefundDetailId() + "," + orderDetail.getProDetailId());
            }
            // 判断所有商品是否都退款了
            int expProNum = expDetail.getDetailIds().split(",").length;
            int refundProNum = expDetail.getRefundDetailId().split(",").length;
            if (expProNum == refundProNum) {
                expDetail.setRefundStatus(StaticUtils.STATUS_YES);
            }
        } catch (Exception e) {
            throw new ThrowJsonException("退款失败：" + e.getMessage());
        }
        int i = orderExpDetailMapper.updateById(expDetail);
        if (i < 1) {
            throw new ThrowJsonException("退款失败：ID【" + expDetail.getId() + "】的订单收发货信息处理失败");
        }

        // 如果是待发货——返回库存
        if (calcuUtils.isEquals(order.getOrderStatus(), OrderStatusEnums.NEED_SEND.getId())) {
            orderListerService.handleQty(orderDetail);
        }

        // 运费
        BigDecimal expMoney = BigDecimal.ZERO;
        // 操作退款金额——以及全部订单详情退款完成的话需要修改订单主表状态
        QueryWrapper<OrderDetail> wrapper = new QueryWrapper<OrderDetail>();
        wrapper.eq("order_code", orderDetail.getOrderCode()).eq("refund", StaticUtils.STATUS_NO);
        // 未退款数量
        int noRefundNum = orderDetailService.count(wrapper);
        if (noRefundNum == 0) {
            // 如果全部退款，并且订单未发货才退运费
            if (calcuUtils.isEquals(order.getOrderStatus(), OrderStatusEnums.NEED_SEND.getId())) {
                expMoney = order.getExpMoney();
            }
            // 全部退款
            order.setOrderStatus(OrderStatusEnums.REFUND.getId());
            // 修改订单状态
            orderMainService.updateById(order);
        }

        QueryWrapper<CPayLog> payWrapper = new QueryWrapper<>();
        payWrapper.eq("pay_code", order.getPayCode());
        CPayLog cPayLog = cPayLogService.getOne(payWrapper);
        if (cPayLog == null) {
            throw new ThrowJsonException("退款失败：支付单号【" + order.getPayCode() + "】的交易信息不存在");
        }
        // 处理金额原路退还
        // 支付方式
        Integer payType = order.getPayType();
        // 支付渠道
        Integer payChannel = order.getPayChannel();
        // 退款金额
        BigDecimal refund = orderDetail.getGoodMoney();
        refund = calcuUtils.sub(refund, orderDetail.getDiscountMoney(), 2);
        refund = calcuUtils.sub(refund, orderDetail.getCouponMoney(), 2);
        refund = calcuUtils.sub(refund, orderDetail.getOtherMoney(), 2);

        // 加上运费
        refund = calcuUtils.add(refund, expMoney, 2);
        // 生成退款单号
        String refundcode = calcuUtils.getOrderCode("R");
        String flag = "";

        //先处理系统内的业务
        // 退款——将冻结的积分和金额返回
        FreezeVo freeze = new FreezeVo();
        freeze.setBid(order.getBid());
        freeze.setCid(order.getCid());
        freeze.setType(FreezeTypeEnums.ORDER_ONLINE_FREEZE.getId());
        freeze.setPayCode(order.getPayCode());
        freeze.setOrderDetailId(orderDetailId);
        flag = accountChangeService.handleFreezeReturn(freeze);
        if (!StringUtils.isEmpty(flag)) {
            throw new ThrowJsonException("退款失败：" + flag);
        }

        //TODO 模式相关退款
        modeService.modeRefundMain(orderDetailId);

        // 如果是余额
        if (calcuUtils.isEquals(PayTypeEnums.PAY_MONEY.getId(), payType)) {
            flag = accountChangeService.insertCMoneyDetail(order.getCid(), HandleTypeEnums.ORDER_REFUND.getId(), StaticUtils.PAY_IN,
                    order.getPayCode(), refund, HandleTypeEnums.ORDER_REFUND.getName(), null);
            if (StringUtils.isNotBlank(flag)) {
                flag = "【余额退款】" + flag;
            }
        }
        // 如果是微信
        if (calcuUtils.isEquals(PayTypeEnums.PAY_WX.getId(), payType)) {
            // 微信以分为单位
            refund = calcuUtils.mul(refund, new BigDecimal(100), 0);
            // 判断渠道
            // 订单已经支付的总额
            BigDecimal totalmoney = calcuUtils.mul(order.getPayMoney(), new BigDecimal(100), 0);
            if (calcuUtils.isEquals(PayChannlEnums.APP.getId(), payChannel)) {
                flag = WxPayUtils.getInstance().getPayParaRefundApp(order.getTransCode(), refundcode, String.valueOf(totalmoney), String.valueOf(refund));
                if (StringUtils.isNotBlank(flag)) {
                    flag = "【微信APP】" + flag;
                }
            } else {
                flag = WxPayUtils.getInstance().getPayParaRefund(order.getTransCode(), refundcode, String.valueOf(totalmoney), String.valueOf(refund));
                if (StringUtils.isNotBlank(flag)) {
                    flag = "【微信H5】" + flag;
                }
            }
        }
        // 如果是支付宝
        if (calcuUtils.isEquals(PayTypeEnums.PAY_ZFB.getId(), payType)) {
            InfoAli ali = RedisUtils.getInstance().getAliInfo();
            if (calcuUtils.isEquals(PayChannlEnums.APP.getId(), payChannel)) {
                flag = AlipayUtils.aliAppRefund(ali, order.getPayCode(), order.getTransCode(),
                        String.valueOf(refund));
                if (StringUtils.isNotBlank(flag)) {
                    flag = "【支付宝APP】" + flag;
                }
            } else {
                flag = AlipayUtils.aliWebRefund(ali, order.getPayCode(), order.getTransCode(),
                        String.valueOf(refund));
                if (StringUtils.isNotBlank(flag)) {
                    flag = "【支付宝H5】" + flag;
                }
            }
        }
        if (!StringUtils.isEmpty(flag)) {
            throw new ThrowJsonException("退款失败：" + flag);
        }

        //处理消息推送
//		String token = redisUtilsService.getKey(order.getCid() + "_token");
//		PushVo pushVo = new PushVo(token, MsgUtils.JPUSH_0005, PushTypeEnums.REFUND_NOTICE.getId(),
//				order.getOrderCode(),new String[]{order.getOrderCode(),orderDetail.getProName()},order.getCid());
//		pushService.pushMessageById(pushVo);
    }

    @Override
    public RestResponse handleBusRefund(String orderCode, Integer checkId) {
        OrderMain order = orderMainService.getByOrderCode(orderCode);
        if (order == null) {
            return GetRest.getFail("订单不存在");
        }
        // 校验订单是否属于该店铺
        BLogin bLogin = bLoginService.getById(checkId);
        if (bLogin == null || !CalcuUtils.getInstance().isEquals(order.getBid(), bLogin.getBid())) {
            return GetRest.getFail("非法操作");
        }
        // 操作订单详情数据
        List<OrderDetail> orderDetails = orderDetailService.listByOrderCode(order.getOrderCode());
        for (OrderDetail detail : orderDetails) {
            // 如果当前有退款申请
            QueryWrapper<OrderRefundLog> wrapper = new QueryWrapper<OrderRefundLog>();
            wrapper.eq("refund_code", detail.getRefundCode()).ne("status", StaticUtils.STATUS_SUCCESS);
            OrderRefundLog refund = super.getOne(wrapper);
            if (refund != null) {
                refund.setCheckTime(new Date());
                refund.setCheckId(checkId);
                refund.setStatus(StaticUtils.STATUS_SUCCESS);
                boolean result = super.updateById(refund);
                if (!result) {
                    throw new ThrowJsonException("操作失败");
                }
            }
            // 处理订单
            handleOrderRefund(detail.getId(), null);
        }
        return GetRest.getSuccess("退款成功");
    }

    @Override
    public IPage<RefundVo> queryRefundList(BasePage<RefundVo> page, RefundVo refund) {
        IPage<RefundVo> refundPage = orderRefundLogMapper.queryRefundList(page, refund);
        for (RefundVo vo : refundPage.getRecords()) {
            vo.setStatusName(RefundStatusEnums.getName(vo.getStatus()));
        }
        return refundPage;
    }

    @Override
    public RefundVo getRefundDetail(String refundCode) {
        RefundVo refund = orderRefundLogMapper.getRefundDetail(refundCode);
        if (refund != null) {
            refund.setStatusName(RefundStatusEnums.getName(refund.getStatus()));
            refund.setPayTypeName(PayTypeEnums.getName(refund.getPayType()));
        }
        return refund;
    }

    @Override
    public RestResponse cancelRefund(Integer refundId, String cancelReason) {
        OrderRefundLog refund = super.getById(refundId);
        if (refund == null) {
            return GetRest.getFail("退款数据不存在");
        }
        // 将退款数据改为取消状态
        refund.setStatus(RefundStatusEnums.CANCEL.getId());
        refund.setCancelTime(new Date());
        refund.setCancelReason(cancelReason);
        boolean result = super.updateById(refund);
        if (result) {
            // 同步订单详情退款状态
            OrderDetail orderDetail = orderDetailService.getById(refund.getOrderDetailId());
            if (orderDetail == null) {
                throw new ThrowJsonException("取消退款失败 Code:001");
            }
            orderDetail.setRefund(StaticUtils.STATUS_NO);
            result = orderDetailService.updateById(orderDetail);
            if (!result) {
                throw new ThrowJsonException("取消退款失败 Code:002");
            }

            CalcuUtils calcuUtils = CalcuUtils.getInstance();
            QueryWrapper<OrderMain> orderMainQueryWrapper = new QueryWrapper<>();
            orderMainQueryWrapper.eq("order_code", orderDetail.getOrderCode());
            OrderMain orderMain = orderMainService.getOne(orderMainQueryWrapper);

            //取消退款 平台拨还用户创业分
            if (orderMain != null && orderDetail.getPoint() != null && BigDecimal.ZERO.compareTo(orderDetail.getPoint()) < 0) {
                BigDecimal totalPoint = calcuUtils.mul(orderDetail.getPoint(), new BigDecimal(orderDetail.getQty()), 2);
                String msg = iAccountChangeService.insertCPointDetail(orderMain.getCid(), HandleTypeEnums.ORDER_REFUND_REFUSE.getId(), StaticUtils.PAY_IN,
                        orderMain.getPayCode(), totalPoint, HandleTypeEnums.getName(HandleTypeEnums.ORDER_REFUND_REFUSE.getId()), orderMain.getCid());
                if (!StringUtils.isEmpty(msg)) {
                    throw new ThrowJsonException(msg);
                }
            }

            return GetRest.getSuccess("取消退款成功");
        }

        return GetRest.getFail("取消退款失败");
    }

    @Override
    public RefundVo getRefundApplyPage(Integer orderDetailId) {
        CalcuUtils calcuUtils = CalcuUtils.getInstance();
        OrderDetail orderDetail = orderDetailService.getById(orderDetailId);
        if (orderDetail == null) {
            throw new ThrowJsonException("订单不存在");
        }
        if (calcuUtils.isEquals(orderDetail.getIsRefund(), StaticUtils.STATUS_NO)) {
            throw new ThrowJsonException("该商品不支持退款");
        }
        OrderMain order = orderMainService.getByOrderCode(orderDetail.getOrderCode());
        if (order == null) {
            throw new ThrowJsonException("订单不存在");
        }
        if (!(order.getOrderStatus() >= OrderStatusEnums.NEED_SEND.getId() && order.getOrderStatus() < OrderStatusEnums.OVER.getId())) {
            throw new ThrowJsonException("当前状态不能申请退款");
        }
        if (calcuUtils.isEquals(order.getPayType(), PayTypeEnums.PAY_POINT.getId())) {
            throw new ThrowJsonException("积分商品不能退款");
        }

        if (calcuUtils.isEquals(orderDetail.getRefund(), StaticUtils.STATUS_YES)) {
            throw new ThrowJsonException("已退款或退款申请中");
        }
        RefundVo refundVo = new RefundVo();
        BeanUtils.copyProperties(orderDetail, refundVo);
        // 还没有收货——仅退款
        if (order.getOrderStatus() < OrderStatusEnums.HAS_SEND.getId()) {
            refundVo.setApplyType(StaticUtils.ONLY_REFUND);
        } else {
            // 退款退货
            refundVo.setApplyType(StaticUtils.ALL_REFUND);
        }
        refundVo.setProPrice(orderDetail.getPrice());
        refundVo.setProQty(orderDetail.getQty());
        // 退款金额
        BigDecimal refund = orderDetail.getGoodMoney();
        refund = calcuUtils.sub(refund, orderDetail.getDiscountMoney(), 2);
        refund = calcuUtils.sub(refund, orderDetail.getCouponMoney(), 2);
        refund = calcuUtils.sub(refund, orderDetail.getOtherMoney(), 2);
        refundVo.setRefundMoney(refund);
        return refundVo;
    }

    @Override
    public RestResponse handleRefundApply(OrderRefundLog refundLog) {
        CalcuUtils calcuUtils = CalcuUtils.getInstance();
        if (refundLog.getOrderDetailId() == null) {
            return GetRest.getFail("提交申请失败");
        }
        OrderDetail orderDetail = orderDetailService.getById(refundLog.getOrderDetailId());
        if (orderDetail == null) {
            throw new ThrowJsonException("订单不存在");
        }
        if (calcuUtils.isEquals(orderDetail.getIsRefund(), StaticUtils.STATUS_NO)) {
            throw new ThrowJsonException("该商品不支持退款");
        }
        OrderMain order = orderMainService.getByOrderCode(orderDetail.getOrderCode());
        if (order == null) {
            throw new ThrowJsonException("订单不存在");
        }
        if (order.getOrderStatus() != OrderStatusEnums.NEED_SEND.getId()) {
            throw new ThrowJsonException("当前状态不能申请退款");
        }
        if (calcuUtils.isEquals(order.getPayType(), PayTypeEnums.PAY_POINT.getId())) {
            throw new ThrowJsonException("积分商品不能退款");
        }
        if (refundLog.getApplyType() == null) {
            return GetRest.getFail("请选择退款方式");
        }

        if (StringUtils.isBlank(refundLog.getRefundReason())) {
            return GetRest.getFail("请选择退款原因");
        }

        if (refundLog.getRefundRemark() != null && refundLog.getRefundRemark().length() > 100) {
            return GetRest.getFail("退款描述不能大于100个字");
        }

        QueryWrapper<OrderRefundLog> queryWrapper = new QueryWrapper<OrderRefundLog>();
        queryWrapper.eq("order_detail_id", refundLog.getOrderDetailId());
        queryWrapper.orderByDesc("create_time");
        List<OrderRefundLog> refundList = orderRefundLogMapper.selectList(queryWrapper);
        OrderRefundLog queryRefundLog = null;
        if (refundList != null && refundList.size() > 0) {
            queryRefundLog = refundList.get(0);
        }
        if (queryRefundLog != null) {
            if (!(calcuUtils.isEquals(queryRefundLog.getStatus(), StaticUtils.STATUS_FAIL)
                    || calcuUtils.isEquals(queryRefundLog.getStatus(), StaticUtils.STATUS_TIME_OUT))) {
                return GetRest.getFail("已退款或退款申请中");
            }
        }
        // 退款编号
        String refundCode = calcuUtils.getOrderCode("RD");
        refundLog.setBid(order.getBid());
        refundLog.setOrderCode(order.getOrderCode());
        refundLog.setRefundCode(refundCode);
        refundLog.setStatus(StaticUtils.STATUS_APPLY);
        // 退款金额
        BigDecimal refund = orderDetail.getGoodMoney();
        refund = calcuUtils.sub(refund, orderDetail.getDiscountMoney(), 2);
        refund = calcuUtils.sub(refund, orderDetail.getCouponMoney(), 2);
        refund = calcuUtils.sub(refund, orderDetail.getOtherMoney(), 2);
        refundLog.setRefundMoney(refund);
        refundLog.setPayType(order.getPayType());
        int result = orderRefundLogMapper.insert(refundLog);
        if (result < 1) {
            return GetRest.getFail("提交申请失败");
        }
        // 修改订单详情退款信息
        orderDetail.setRefund(StaticUtils.STATUS_YES);
        orderDetail.setRefundCode(refundCode);
        boolean update = orderDetailService.updateById(orderDetail);
        if (!update) {
            throw new ThrowJsonException("提交申请失败");
        }

        //用户扣除创业分给平台
        if (orderDetail.getPoint() != null && BigDecimal.ZERO.compareTo(orderDetail.getPoint()) < 0) {
            BigDecimal totalPoint = calcuUtils.mul(orderDetail.getPoint(), new BigDecimal(orderDetail.getQty()), 2);
            String msg = iAccountChangeService.insertCPointDetail(order.getCid(), HandleTypeEnums.ORDER_REFUND_APPLY.getId(), StaticUtils.PAY_OUT,
                    order.getPayCode(), totalPoint, HandleTypeEnums.getName(HandleTypeEnums.ORDER_REFUND_APPLY.getId()), order.getCid());
            if (!StringUtils.isEmpty(msg)) {
                throw new ThrowJsonException(msg);
            }
        }
        return GetRest.getSuccess("提交申请成功");
    }

    @Override
    public List<OrderRefundLog> queryRefundHistory(Integer orderDetailId) {
        CalcuUtils calcuUtils = CalcuUtils.getInstance();
        List<OrderRefundLog> list = new ArrayList<OrderRefundLog>();
        // 查询条件
        QueryWrapper<OrderRefundLog> queryWrapper = new QueryWrapper<OrderRefundLog>();
        queryWrapper.eq("order_detail_id", orderDetailId);
        List<OrderRefundLog> refundList = orderRefundLogMapper.selectList(queryWrapper);
        for (OrderRefundLog refund : refundList) {
            CCustomer customer = cCustomerService.getById(refund.getCid());
            if (customer == null) {
                throw new ThrowJsonException("用户数据有误");
            }
            OrderRefundLog cancelRefund = new OrderRefundLog();
            // 退款申请
            cancelRefund.setCHeadurl(customer.getHeadurl());
            cancelRefund.setCNickName(customer.getNickName());
            cancelRefund.setHandleTime(refund.getCreateTime());
            cancelRefund.setApplyTypeName(refund.getApplyType() == 1 ? "仅退款" : "退款退货");
            cancelRefund.setRefundMoney(refund.getRefundMoney());
            cancelRefund.setRefundReason(refund.getRefundReason());
            cancelRefund.setRefundRemark(refund.getRefundRemark());
            cancelRefund.setStatus(StaticUtils.STATUS_APPLY);
            if (!StringUtils.isEmpty(refund.getRefundImgs())) {
                cancelRefund.setRefundImgList(Arrays.asList(refund.getRefundImgs().split(",")));
            }
            list.add(cancelRefund);
            cancelRefund = new OrderRefundLog();
            // 退款取消
            if (calcuUtils.isEquals(refund.getStatus(), StaticUtils.STATUS_TIME_OUT)) {
                cancelRefund.setCHeadurl(customer.getHeadurl());
                cancelRefund.setCNickName(customer.getNickName());
                cancelRefund.setHandleTime(refund.getCancelTime());
                cancelRefund.setStatus(StaticUtils.STATUS_TIME_OUT);
                cancelRefund.setCancelReason("其他");
                list.add(cancelRefund);
            } else if (calcuUtils.isEquals(refund.getStatus(), StaticUtils.STATUS_FAIL)
                    || calcuUtils.isEquals(refund.getStatus(), StaticUtils.STATUS_SUCCESS)) {
                // 退款驳回或退款成功
                if (calcuUtils.isEquals(refund.getCheckId(), StaticUtils.STATUS_NO)) {
                    // 平台操作
                    cancelRefund.setCHeadurl("");
                    cancelRefund.setCNickName("平台操作");
                } else {
                    BLogin bLogin = bLoginService.getById(refund.getCheckId());
                    if (bLogin == null) {
                        throw new ThrowJsonException("数据有误");
                    }
                    cancelRefund.setCHeadurl(bLogin.getHeadurl());
                    cancelRefund.setCNickName(bLogin.getNickName());
                }
                cancelRefund.setHandleTime(refund.getCheckTime());
                cancelRefund.setStatus(refund.getStatus());
                if (calcuUtils.isEquals(refund.getStatus(), StaticUtils.STATUS_SUCCESS)) {
                    cancelRefund.setRefundMoney(refund.getRefundMoney());
                    cancelRefund.setPayTypeName(PayTypeEnums.getName(refund.getPayType()));
                } else {
                    cancelRefund.setRejectRemark(refund.getRejectRemark());
                    cancelRefund.setRejectReason("其他");
                }
                list.add(cancelRefund);
            }
        }
        return list;
    }

    @Override
    public RestResponse handleDirectRefund(Integer cid, Integer orderDetailId, String reason) {
        handleOrderRefund(orderDetailId, cid);
        return GetRest.getSuccess("退款成功");
    }

}
